﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using MySql.Data.MySqlClient;
using System.Xml;
using System.Data;

namespace TKWeb
{
	public partial class RecData2 : System.Web.UI.Page
	{
		static List<string> s_tableNameCache = new List<string>();
		public static void EnsureTableStruct(string tableName, string sql)
		{
			if (s_tableNameCache.Contains(tableName))
			{
				return;
			}

			MySqlParameter[] pars = new MySqlParameter[]{
				new MySqlParameter("@table_name", tableName)
			};

			long count = Global.DBAccess.GetCount("SELECT COUNT(*) FROM information_schema.TABLES WHERE table_name=@table_name", pars);
			if (count == 0)
			{
				Global.DBAccess.ExecuteNonQuery(sql);
				s_tableNameCache.Add(tableName);
			}
		}

		private string BuildSql(string tableName, int fileId)
		{
			DataTable dt = Global.DBAccess.GetTable("select * from crawl_file_field where fileId=@fileId", new MySqlParameter[]{
				new MySqlParameter("fileId", fileId)
			});

			StringBuilder sb = new StringBuilder();


			sb.Append("CREATE TABLE " + tableName.ToUpper());
			sb.Append("(");
			sb.Append("DATA_ID             INT NOT NULL AUTO_INCREMENT,");
			sb.Append("HASH             INT NOT NULL,");
			sb.Append("STATUS             INT NOT NULL DEFAULT 0,");

			int i=0;
			foreach (DataRow dr in dt.Rows)
			{
				if(i > 0)
				{
					sb.Append(",");
				}
				string code = dr["code"].ToString();
				string dataType = dr["data_type"].ToString();
				string dataLen = dr["data_len"].ToString();
				string dataPreci = dr["data_preci"].ToString();

				string dataTypeName = string.Empty;
				switch(dataType){
					case "1":
						dataTypeName = string.Format("VARCHAR({0})", dataLen == "0" ? "50" : dataLen);
						break;

					case "2":
						dataTypeName = string.Format("INT({0})", dataLen == "0" ? "11" : dataLen);
						break;

					case "3":
						dataTypeName = string.Format("NUMERIC({0},{1})", dataLen == "0" ? "10" : dataLen,dataPreci);
						break;

					case "4":
						dataTypeName = "DATETIME";
						break;

					case "5":
						dataTypeName = "LONGTEXT";
						break;
				}
				sb.AppendFormat("{0} {1}", code.ToUpper(), dataTypeName);
				i++;
			}
			sb.Append(");");
			return sb.ToString();
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			byte[] buffer = Request.BinaryRead(Request.TotalBytes);
			string strXml = System.Text.Encoding.UTF8.GetString(buffer);
			if (string.IsNullOrEmpty(strXml))
			{
				return;
			}
			XmlDocument doc = new XmlDocument();
			doc.LoadXml(strXml);

			int fileId = Convert.ToInt32(doc.DocumentElement.Attributes["fileid"].Value);
			string tableName = "GATHER_DATA_" + fileId;
			EnsureTableStruct(tableName, BuildSql(tableName, fileId));

			string url = doc.DocumentElement.Attributes["url"].Value;
			int hash = (url + "$" + fileId).GetHashCode();

			List<MySqlParameter> pars = new List<MySqlParameter>();

			DataTable dt = Global.DBAccess.GetTable("select * from crawl_file_field where fileId=@fileId", new MySqlParameter[]{
				new MySqlParameter("fileId", fileId)
			});

			StringBuilder sb = new StringBuilder();
			int count = Global.DBAccess.GetCount(string.Format("select count(*) from {0} where hash=@hash", tableName), new MySqlParameter("hash", hash));
			if (count == 0)
			{
				sb.AppendFormat("insert into {0}(", tableName);
				int i = 0;
				foreach (DataRow dr in dt.Rows)
				{
					if (i > 0)
					{
						sb.Append(",");
					}
					string code = dr["code"].ToString();
					sb.Append(code);
					i++;
				}

				sb.Append(") values(");
				int j = 0;
				foreach (DataRow dr in dt.Rows)
				{
					if (j > 0)
					{
						sb.Append(",");
					}
					string code = dr["code"].ToString();
					sb.Append("@" + code);
					j++;
				}
				sb.Append(")");
			}
			else
			{
				sb.AppendFormat("update {0} set ", tableName);
				int i = 0;
				foreach (DataRow dr in dt.Rows)
				{
					if (i > 0)
					{
						sb.Append(",");
					}
					string code = dr["code"].ToString();
					sb.Append(code + "=@" + code);
					i++;
				}
				sb.Append("where hash=@hash");
			}

			pars.Add(new MySqlParameter("hash", hash));
			foreach (XmlNode n in doc.DocumentElement.ChildNodes)
			{
				pars.Add(new MySqlParameter(n.Name, n.InnerText));
			}
			Global.DBAccess.ExecuteNonQuery(sb.ToString(), pars.ToArray());
		}
	}
}